package cc.sunni.sell.controller;

import cc.sunni.sell.config.SellProperties;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.service.WxOAuth2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author jl
 * @since 2021/1/19 20:36
 */
@Controller
@RequestMapping("/wechat")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WeChatController {
    private final WxOAuth2Service wxOAuth2Service;

    /**
     * 第一步:构造第三方使用网站应用授权登录的url
     *
     * @param returnUrl 需要网络协议http://或http://开头.注意区分配置网页授权协议是要去掉网络协议的
     */
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) throws UnsupportedEncodingException {
        String redirectUri = SellProperties.DOMAIN + "/sell/wechat/userInfo";
        /*
         * redirectUri 用户授权完成后的重定向链接，无需urlencode, 方法内会进行encode
         * scope       应用授权作用域
         * state       非必填，用于保持请求和回调的状态，授权请求后原样带回给第三方
         */
        String authUrl = wxOAuth2Service.buildAuthorizationUrl(redirectUri, WxConsts.OAuth2Scope.SNSAPI_BASE, URLEncoder.encode(returnUrl, "UTF-8"));
        return "redirect:" + authUrl;
    }

    /**
     * 第二步:用户同意授权，获取code和state
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl) throws WxErrorException {
        // 第三步：通过code换取网页授权access_token
        WxOAuth2AccessToken accessToken = wxOAuth2Service.getAccessToken(code);
        String openId = accessToken.getOpenId();
        return "redirect:" + returnUrl + "?openid=" + openId;
    }


}
